﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using System;

[AddComponentMenu("UI/LongPressButton")]
public class UILongPressButton : Selectable, IPointerDownHandler, IPointerExitHandler, IPointerUpHandler
{
    public Action onPressStart = null;
    public Action onPress = null;
    public Action<float> onPressOver = null;

    protected override void OnDestroy()
    {
        base.OnDestroy();

        onPressStart = null;
        onPress = null;
        onPressOver = null;
    }

    float interval = 0.1f;
    float longPressDelay = 0.5f;

    private bool isPressStart = false;
    private bool isTouchDown = false;
    private bool isLongpress = false;
    private float touchBegin = 0;
    private float lastInvokeTime = 0;

    // Update is called once per frame
    void Update()
    {
        if (isTouchDown && IsPressed() && interactable)
        {
            if (isLongpress)
            {
                if (Time.time - lastInvokeTime > interval)
                {
                    if (isPressStart)
                    {
                        isPressStart = false;
                        if (onPressStart != null)
                        {
                            onPressStart();
                        }
                    }

                    if (onPress != null) onPress();
                    lastInvokeTime = Time.time;
                }
            }
            else
            {
                isLongpress = Time.time - touchBegin > longPressDelay;
            }
        }
    }

    public override void OnPointerDown(PointerEventData eventData)
    {
        base.OnPointerDown(eventData);
        touchBegin = Time.time;
        isPressStart = true;
        isTouchDown = true;
    }

    public override void OnPointerExit(PointerEventData eventData)
    {
        base.OnPointerExit(eventData);
        isTouchDown = false;
        isLongpress = false;
        isPressStart = false;
    }

    public override void OnPointerUp(PointerEventData eventData)
    {
        base.OnPointerUp(eventData);
        isTouchDown = false;
        if (isLongpress)
        {
            if (onPressOver != null)
            {
                onPressOver(lastInvokeTime - touchBegin);
            }
        }
        isLongpress = false;
        isPressStart = false;
    }
}